package com.atguigu.gmall.order.receiver;


import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;


@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    @Autowired
    private RabbitService rabbitService;


    /**
     * 延迟队列查看订单是否支付
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void orderCancle(Long orderId, Message message, Channel channel) {
        try {
            if (orderId != null) {
    //            更该订单状态
                OrderInfo orderInfo = orderService.getById(orderId);
                if (orderInfo != null && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())) {

    //                查询本地是否存在交易记录
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getTrackingNo());
                    if (null!=paymentInfo && paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())){
    //                    查询支付宝是否有交易状态
                        Boolean result = paymentFeignClient.checkPayment(orderId);
                        if (result){
    //                        支付宝存在交易记录
    //                        判断是否能够关闭支付状态
                            Boolean flag = paymentFeignClient.closePay(orderId);
                            if (flag){
    //                        未支付
                                orderService.updateOrderStatus(orderId,"2");
                            }else {
    //                            已支付,无需处理
    //                            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
    //                                    MqConst.ROUTING_PAYMENT_PAY,orderId);

                            }
                        }else {
    //                        支付宝不存在交易记录,关闭支付状态,订单合支付
                            orderService.updateOrderStatus(orderId,"2");
                        }
                    }
    //                更改订单
                    orderService.updateOrderStatus(orderId,"1");
                }
            }
//        手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }

    }


    /**
     * 支付成功修改订单状态
     * @param orderId
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void updateOrderStatus(Long orderId,Message message,Channel channel) throws IOException {
        if (orderId!=null){

//            判断支付状态
            OrderInfo orderInfo = orderService.getOrderInfo(orderId);
            if (orderInfo != null && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())) {
//                更改订单状态
                orderService.updateOrderStatus(orderId);

//                更改订单状态，减库存
                orderService.sendOrderStatus(orderId);
            }
        }
//        确认消息发送
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    /**
     * 更改库存状态
     * @param
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void updateOrderStatusCount(String mesag,Message message,Channel channel) throws IOException {
        if (StringUtils.isNotEmpty(mesag)) {
            Map map = JSON.parseObject(mesag, Map.class);
//            获取订单id和订单状态
            String orderId = (String)map.get("orderId");
            String status = (String)map.get("status");
//            判断状态是否成功
            if ("DEDUCTED".equals(status)){
//                修改库存状态
                orderService.updateOrderStatusList(Long.valueOf(orderId), ProcessStatus.WAITING_DELEVER);
            }else {
//                通知已经发货，去补货
                orderService.updateOrderStatusList(Long.valueOf(orderId),ProcessStatus.STOCK_EXCEPTION);
//                mq保证数据的最终一致
            }
        }
//        手动确认消息接受
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}


